<?php
/********************************************************************
Product    : Plotalot
Date       : 15 April 2011
Copyright  : Les Arbres Design 2010-2011
Contact    : http://extensions.lesarbresdesign.info
Licence    : GNU General Public License
*********************************************************************/

defined('_JEXEC') or die('Restricted Access');

jimport('joomla.application.component.model');
jimport('joomla.html.pagination');

class PlotalotModelChart extends JModel
{
var $_app = null;					// constructor gets the app
var $_data;
var $_pagination = null;

function __construct()
{
	parent::__construct();
	$this->_app = &JFactory::getApplication();
}

//-------------------------------------------------------------------------------
// initialise data for a new row
//
function initData($chart_type)
{
	$this->_data = new stdClass();
	$this->_data->id = 0;
	$this->_data->published = 1;
	$this->_data->chart_type = $chart_type;
	$this->_data->chart_name = '';
	$this->_data->chart_title = '';
	$this->_data->chart_title_colour = '';
	$this->_data->chart_title_font_size = '';
	$this->_data->x_size = 512;
	$this->_data->y_size = 256;
	if ($this->_data->chart_type == CHART_TYPE_TABLE)
		{
		$this->_data->chart_css_style = 'border="1" cellspacing="0" cellpadding="2"';
		$this->_data->x_size = 0;
		$this->_data->y_size = 100;
		$this->_data->legend_type = true;
		}
	if ($this->_data->chart_type == CHART_TYPE_LINE)
		{
		$this->_data->chart_css_style = 'alt=" "';
		$this->_data->legend_type = LEGEND_BOTTOM;
		}
	$this->_data->back_style = 0;
	$this->_data->back_colour = '';
	$this->_data->back_colour_2 = '';
	$this->_data->db_host = 'localhost';
	$this->_data->db_name = '';
	$this->_data->db_user = '';
	$this->_data->db_pass = '';
	$this->_data->num_plots = 1;
	$this->_data->show_grid = true;
	$this->_data->show_raw_data = false;
	$this->_data->x_title = '';
	$this->_data->x_start = '';
	$this->_data->x_end = '';
	$this->_data->x_format = FORMAT_NUM_UK_0;
	$this->_data->x_column = '';
	$this->_data->x_labels = -1;
	$this->_data->y_title = '';
	$this->_data->y_start = '';
	$this->_data->y_end = '';
	$this->_data->y_format = FORMAT_NUM_UK_0;
	$this->_data->y_labels = -1;
	$this->_data->extra_parms = '';
	$this->_data->plots = '';
	$this->_data->plot_array = array();
	$this->_data->plot_array[0]['enable'] = 1;
	return $this->_data;
}

//-------------------------------------------------------------------------------
// validate the data
//
function check()
{
	if ($this->_data->chart_name == '')
		{
		$this->_app->enqueueMessage(JText::_('COM_PLOTALOT_CHART_NAME_BLANK'), 'error');
		return false;
		}
		
	if ($this->_data->chart_type < CHART_TYPE_MAX_TABLE)
		return true;
		
	if ($this->_data->num_plots < 1)
		{
		$this->_data->num_plots = 1;
		$this->_app->enqueueMessage(JText::_('COM_PLOTALOT_MIN_PLOTS'), 'error');
		return false;
		}
		
	if ($this->_data->num_plots > CHART_MAX_PLOTS)
		{
		$this->_data->num_plots = CHART_MAX_PLOTS;
		$this->_app->enqueueMessage(JText::_('COM_PLOTALOT_MAX_PLOTS').' '.CHART_MAX_PLOTS, 'error');
		return false;
		}
	return true;
}

//-------------------------------------------------------------------------------
// Store a record
//
function store()
{	
	if (JRequest::getVar('show_raw_data',0) == 0)	// default checkbox values
		JRequest::setVar('show_raw_data',0);
	if (JRequest::getVar('show_grid',0) == 0)
		JRequest::setVar('show_grid',0);
	if (JRequest::getVar('legend_type',0) == 0)
		JRequest::setVar('legend_type',0);
		
	$postData = JRequest::get('post',2);	// get $_POST data, allow raw because we need < and >

	$row =& $this->getTable();				// get instance of relevant Table object
	if (!$row->bind($postData,'plots'))		// copy post data to table object but ignore plots property
		{
		$this->_app->enqueueMessage($row->getError(), 'error');
		return false;
		}
	$all_plots = $this->make_all_plots($postData);	// make the combined name=value string
	$row->plots = addslashes($all_plots);			// and store it in the table object
	foreach ($row->getProperties() as $k => $v)		// copy the table properties back to our _data
		$this->_data->$k = $v;
	$plot_array = array();
	$this->expand_plots($all_plots, $this->_data->plot_array);		// create the plot arrays

	if (!$this->check())				// Validate the data
		return false;					// The table has enqueued an error message

	if (!$row->store())					// Save the data to the database
		{	
		$this->_app->enqueueMessage($this->_db->stderr(), 'error');
		return false;
		}

	$new_id = $this->_db->insertId();	// if this was an update, get the id of the new row
	if ($new_id > 0)
		$this->_data->id = $new_id;		// and store it in our _data
	return true;
}

//-------------------------------------------------------------------------------
// convert the plots_ post data fields to the combined plots field in name=value format
// note we can't allow newlines in the data but we can take out the \n and leave the \r
// returns the combined string
//
function make_all_plots($postData)
{
	$plots = '';
	foreach ($postData as $k => $v)		// copy post data plot_ fields to table plots field
		if (strncmp($k,'plot_',5) == 0)
			$plots .= $k.'='.str_replace("\n","",$v)."\n";
	return $plots;
}

//-------------------------------------------------------------------------------
// expand the combined name=value format plots field to arrays in the supplied data object
//
function expand_plots(&$source, &$dest)
{
	$params = explode("\n",$source);
	foreach ($params as $param)
		{
		$p = strpos($param,"=");
		if ($p === false)
			continue;			// should never happen
		$key = substr($param,0,$p);
		$value = substr($param,$p+1);
		$field_num = substr($key,5);
		$q = strrpos($field_num,"_");
		$plot_num = substr($field_num,$q+1);
		$field_name = substr($field_num,0,$q);
		$dest[$plot_num][$field_name] = $value;
		}
}

//-------------------------------------------------------------------------------
// Load the data
//
function &getOne($id)
{
	$query = 'SELECT * FROM #__plotalot WHERE id = '.$id;
	$this->_db->setQuery($query);
	$this->_data = $this->_db->loadObject();

	if ($this->_data)				// if no data, default it
		{
		$this->_data->plots = stripslashes($this->_data->plots);
		$this->expand_plots($this->_data->plots, $this->_data->plot_array);
		return $this->_data;
		}
	else
		{
		$this->_app->enqueueMessage(JText::_('COM_PLOTALOT_CHART_NOT_FOUND'), 'error');
		return false;
		}
}

//-------------------------------------------------------------------------------
// return the pagination object
// - should be called after getList()
//
function getPagination()
{
	if ($this->_pagination == Null)
		$this->_pagination = new JPagination(0,0,0);
	return $this->_pagination;
}

//-------------------------------------------------------------------------------
// Load a list of charts
//
function getList()
{
// get the filter states, order states, and pagination variables

	$app = &JFactory::getApplication();
	$filter_state = $app->getUserStateFromRequest(LA_COMPONENT.'.filter_state','filter_state','','word');
	$filter_chart_type = $app->getUserStateFromRequest(LA_COMPONENT.'.filter_chart_type','filter_chart_type',CHART_TYPE_ANY,'int');
	$limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->getCfg('list_limit'), 'int');
	$limitstart = $app->getUserStateFromRequest(LA_COMPONENT.'.limitstart', 'limitstart', 0, 'int');
	$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0); // In case limit has been changed
	$filter_order = $app->getUserStateFromRequest(LA_COMPONENT.'.filter_order', 'filter_order', 'chart_name');
	$filter_order_Dir = $app->getUserStateFromRequest(LA_COMPONENT.'.filter_order_Dir', 'filter_order_Dir', 'asc');

// build the query

	$query_count = "Select count(*) ";
	$query_cols  = "Select * ";
	$query_from  = "From #__plotalot ";

// where

	$query_where = "Where 1";

	switch ($filter_state)
		{
		case 'P':
			$query_where .= " And published = '1'";
			break;
		case 'U':
			$query_where .= " And published = '0'";
			break;
		default:
		}

	switch ($filter_chart_type)
		{
		case CHART_TYPE_ANY:
			break;
		case CHART_TYPE_SINGLE_ITEM:
			$query_where .= " And chart_type = ".CHART_TYPE_SINGLE_ITEM;
			break;
		case CHART_TYPE_TABLE:
			$query_where .= " And chart_type = ".CHART_TYPE_TABLE;
			break;
		case CHART_TYPE_LINE:
			$query_where .= " And chart_type = ".CHART_TYPE_LINE;
			break;
		case CHART_TYPE_SCATTER:
			$query_where .= " And chart_type = ".CHART_TYPE_SCATTER;
			break;
		case CHART_TYPE_PIE:
			$query_where .= " And chart_type in (".CHART_TYPE_PIE_2D.", ".CHART_TYPE_PIE_3D.", ".CHART_TYPE_PIE_2D_V.", ".CHART_TYPE_PIE_3D_V.")";
			break;
		case CHART_TYPE_BAR:
			$query_where .= " And chart_type in (".CHART_TYPE_BAR_H_STACK.", ".CHART_TYPE_BAR_H_GROUP.", ".CHART_TYPE_BAR_V_STACK.", ".CHART_TYPE_BAR_V_GROUP.")";
			break;
		default:
		}

// order by			

	switch ($filter_order)							// validate column name
		{
		case 'id':
		case 'chart_name':
		case 'chart_type':
		case 'db_name':
			break;
		default:
			$filter_order = 'chart_name';
		}

	if (strcasecmp($filter_order_Dir,'ASC') != 0)	// validate 'asc' or 'desc'
		$filter_order_Dir = 'DESC';

	$query_order = " Order by ".$filter_order.' '.$filter_order_Dir;


// get the total row count

	$count_query = $query_count.$query_from.$query_where;
	$this->_db->setQuery($count_query);
	$total = $this->_db->loadResult();
	if ($this->_db->getErrorNum())
		{
		$this->_app->enqueueMessage($this->_db->stderr(), 'error');
		return false;
		}

// setup the pagination object

	$this->_pagination = new JPagination($total, $limitstart, $limit);

//now get the data, within the limits required		

	$main_query = $query_cols.$query_from.$query_where.$query_order;
	$this->_data = $this->_getList($main_query, $limitstart, $limit);
	return $this->_data;
}

//-------------------------------------------------------------------------------
// Delete one or more items
//
function delete()
{
	$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

	$row =& $this->getTable();

	foreach($cids as $cid)
		{
		if (!$row->delete($cid))		// call JTable::delete()
			{
			$this->_app->enqueueMessage($this->_db->stderr(), 'error');
			return false;
			}
		}
	return true;
}

//-------------------------------------------------------------------------------
// $p is 0 if unpublishing, 1 if publishing
//
function publish($p)					
{
	$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

	$row =& $this->getTable();

	foreach($cids as $cid)
		{
		if (!$row->publish($cids, $p))	// call JTable::publish()
			{
			$this->_app->enqueueMessage($this->_db->stderr(), 'error');
			return false;
			}
		}
	return true;
}

}